import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:package_info/package_info.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/base/application.dart';
import 'package:panda/entity/article_list_entity.dart';
import 'package:panda/entity/banner_entity.dart';
import 'package:panda/entity/good_list_entity.dart';
import 'package:panda/entity/native_entity.dart';
import 'package:panda/event/UserInfoEvent.dart';
import 'package:panda/goods/GoodsDetail.dart';
import 'package:panda/goods/UserUpdateGoodsList.dart';
import 'package:panda/goods_by_cat_list/BrandList.dart';
import 'package:panda/goods_by_cat_list/PinPaiListPage.dart';
import 'package:panda/goods_by_cat_list/QiangGou.dart';
import 'package:panda/goods_by_cat_list/SearchGoods.dart';
import 'package:panda/goods_by_cat_list/SelectTopGods.dart';
import 'package:panda/goods_by_cat_list/ZeroGoodsList.dart';
import 'package:panda/jiayouzhan/jyz_pay_page.dart';
import 'package:panda/login/Welcome.dart';
import 'package:panda/main.dart';
import 'package:panda/set/ArticleDetail.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';

import '../base/Constant.dart';
import '../http/Api.dart';
import '../http/HttpUtil.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return HomeFragmentState();
  }
}

class HomeFragmentState extends State<HomePage> with WidgetsBindingObserver {
  List<BannerModelData> bannerData;
  ScrollController scrollController = new ScrollController();
  List<HomeListDataData> articles = new List();
  Timer _timer;
  int current = 0;
  int page = 1;
  String time1 = "", group_id = "1", phone = "";
  // Color currentColor = mainColor;
  EasyRefreshController _controller = EasyRefreshController();
  List<GoodsListDataData> goodsList = new List();
  String token = "";
  bool isCheck = true;
  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
      floatingActionButton: GestureDetector(
        child: Container(
          width: ScreenUtil.getInstance().setHeight(60),
          height: ScreenUtil.getInstance().setHeight(60),
          alignment: Alignment.center,
          child: Text('顶部^',
              style: TextStyle(
                  color: white, fontSize: ScreenUtil.getInstance().setSp(25))),
          decoration: BoxDecoration(
              color: mainColor, borderRadius: BorderRadius.circular(60)),
        ),
        onTap: () {
          scrollController.animateTo(0,
              duration: const Duration(milliseconds: 500),
              curve: Curves.easeOut);
        },
        behavior: HitTestBehavior.opaque,
      ),
      appBar: PreferredSize(
          child: AppBar(
            elevation: 0.0,
            backgroundColor: mainColor,
          ),
          preferredSize: Size.fromHeight(0)),
      body: Container(
        color: Colors.white,
        child: Stack(
          children: <Widget>[
            // 裁切的控件
            ClipPath(
                // 只裁切底部的方法
                // clipper: BottonClipper(),
                child: Container(
              color: mainColor,
              height: ScreenUtil.getInstance().setWidth(DP_300),
            )),
            new NotificationListener(
              onNotification: (ScrollNotification note) {
                if (note is ScrollUpdateNotification && note.depth == 0) {}
                return false;
              },
              child: Container(
                padding: EdgeInsets.only(
                    top: ScreenUtil.getInstance().setHeight(DP_50)),
                child: new EasyRefresh(
                  header: MaterialHeader(),
                  footer: MaterialFooter(),
                  enableControlFinishRefresh: true,
                  enableControlFinishLoad: true,
                  controller: _controller,
                  child: initList(),
                  onLoad: () async {
                    page++;
                    getGoodsList();
                  },
                  onRefresh: () async {
                    page = 1;
                    loadBanner();
                    getGoodsList();
                  },
                ),
              ),
            ),
            Container(
              child: Row(
                children: <Widget>[
                  Container(
                      width: ScreenUtil.getInstance().setHeight(DP_30),
                      height: 1),
                  Container(
                    height: ScreenUtil.getInstance().setHeight(DP_50 + 22),
                    child: Column(
                      children: <Widget>[
                        Image.asset(
                          "images/tem.png",
                          width: ScreenUtil.getInstance().setHeight(DP_50),
                          height: ScreenUtil.getInstance().setHeight(DP_50),
                        ),
                        Text('熊猫新零售',
                            style: TextStyle(
                                color: white,
                                fontSize: ScreenUtil.getInstance().setSp(15))),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Container(
                      height: ScreenUtil.getInstance().setHeight(DP_80),
                      child: Center(
                        child: new GestureDetector(
                          child: Container(
                            padding: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_20),
                                ScreenUtil.getInstance().setWidth(8),
                                ScreenUtil.getInstance().setHeight(DP_20),
                                ScreenUtil.getInstance().setWidth(8)),
                            margin: EdgeInsets.fromLTRB(
                                ScreenUtil.getInstance().setHeight(DP_20),
                                0,
                                ScreenUtil.getInstance().setHeight(DP_20),
                                0),
                            decoration: BoxDecoration(
                                color: Color.fromARGB(120, 255, 255, 255),
                                borderRadius: BorderRadius.circular(25.0)),
                            child: new Row(
                              children: <Widget>[
                                Icon(
                                  Icons.search,
                                  size: 25,
                                  color: Colors.white,
                                ),
                                Text('搜索商品、品牌',
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE)))
                              ],
                            ),
                          ),
                          onTap: () {
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new SearchGoodsListPage();
                            }));
                          },
                        ),
                      ),
                    ),
                  ),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    child: Padding(
                      padding: EdgeInsets.fromLTRB(
                          0, 0, ScreenUtil.getInstance().setWidth(DP_30), 0),
                      child: Text('搜索',
                          style: TextStyle(
                              color: white,
                              fontSize: ScreenUtil.getInstance().setSp(30))),
                    ),
                    onTap: () {
                      Navigator.of(context)
                          .push(new MaterialPageRoute(builder: (context) {
                        return new SearchGoodsListPage();
                      }));
                    },
                  )
                ],
              ),
              decoration: BoxDecoration(color: mainColor),
            ),
          ],
        ),
      ),
    );
  }

  SwiperController contr = new SwiperController();
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    var today = DateTime.now();
    time1 = DateUtils.instance.getFormartData(
        timeSamp: today.millisecondsSinceEpoch, format: "yyyy-MM-dd");
    getString(TOKEN).then((value) {
      token = value;
      getGoodsList();
    });
    APPLIC.eventBus.on<UserInfoEvent>().listen((event) {
      getString(TOKEN).then((value) {
        token = value;
        group_id = APPLIC.userInfoMap['user_msg']['group_id'].toString();
        page = 1;
        phone = APPLIC.userInfoMap['user_msg']['phone'];
        getGoodsList();
      });
    });
    checkVersion();
    loadBanner();
    loadListArticle();
    openInform();
    getHttp();
    // goodsList..add("value")..add("value")..add("value");
  }

  List<NativeData> _datas = List(); //一级分类集合
  void getHttp() async {
    try {
      var response =
          await HttpUtil().post(Api.BaseUrl + "/index.php/wap/Brand/getList");
      Map userMap = json.decode(response.toString());
      var naviEntity = NativeEntity.fromJson(userMap);
      _datas = naviEntity.data;
      _datas.insert(0, NativeData(cat_id: "", name: "首页"));
      setState(() {});
    } catch (e) {
      print(e);
    }
  }

  openInform() async {
    var status = await Permission.notification.status;
    if (status.isGranted) {
      // We didn't ask for permission yet.
    }
    if (status.isUndetermined) {
      // We didn't ask for permission yet.
      Permission.notification.request();
    }
    if (await Permission.location.isRestricted) {
      // The OS restricts access, for example because of parental controls.
    }
    if (status.isPermanentlyDenied) {
      // The user opted to never again see the permission request dialog for this
      // app. The only way to change the permission's status now is to let the
      // user manually enable it in the system settings.
      openAppSettings();
    }
// You can can also directly ask the permission about its status.

    // PermissionStatus permission = await PermissionHandler()
    //     .checkPermissionStatus(PermissionGroup.notification);
    // if (permission == PermissionStatus.granted) {
    // } else {
    //   await PermissionHandler()
    //       .requestPermissions([PermissionGroup.notification]);
    // }
  }

  loadListArticle() async {
    Map map = new Map();
    map['cat_id'] = "2";
    map['p'] = page.toString();
    map['per'] = "10";
    map['sign_type'] = SignType.GET_ARTICLE_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_SYSTEM_ARTICLE, data: getSign(map));
    print(response.data);
    Map userMap = json.decode(response.data);
    HomeListEntity homeServiceEntity = new HomeListEntity.fromJson(userMap);
    if (userMap['code'] == 1 && mounted) {
      articles.addAll(homeServiceEntity.data.datas);
      current = 0;
      startTimer();

      setState(() {});
    }
  }

  void startTimer() {
    const period = const Duration(seconds: 5);
    _timer = Timer.periodic(period, (timer) {
      setState(() {
        if (current == (articles.length - 1)) {
          current = 0;
        } else {
          current++;
        }
      });
    });
  }

  void cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void dispose() {
    super.dispose();
    cancelTimer();
    WidgetsBinding.instance.removeObserver(this);
  }

  getGoodsList() async {
    Map map = new Map();
    map['token'] = APPLIC.userInfoMap == null ? "" : token;
    map['p'] = page.toString();
    map['per'] = "10";
    map['cat_id'] = 4;
    map['date'] = time1;
    map['sign_type'] = SignType.GET_GOODS_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GET_GOODS_LIST, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      GoodsListEntity bannerEntity = new GoodsListEntity.fromJson(userMap);
      setState(() {
        if (page == 1) {
          goodsList.clear();
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(success: true);
          if (bannerEntity.data.datas.length == 0 && page > 1) {
            // Fluttertoast.showToast(msg: "已加载全部");
          }
        }
        goodsList.addAll(bannerEntity.data.datas);
        setState(() {});
      });
    }
  }

  initTop() {
    return Container(
        // padding: EdgeInsets.fromLTRB(ScreenUtil.getInstance().setHeight(DP_30),
        //     0, ScreenUtil.getInstance().setHeight(DP_30), 0),
        margin: EdgeInsets.fromLTRB(
            ScreenUtil.getInstance().setHeight(DP_40 - 15),
            ScreenUtil.getInstance().setHeight(DP_40 - 10),
            ScreenUtil.getInstance().setHeight(DP_40 - 15),
            5),
        height: ScreenUtil.getInstance().setHeight(60) +
            (MediaQuery.of(context).size.width -
                    ScreenUtil.getInstance().setHeight(DP_60)) /
                2.6,
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.only(top: 2),
              height: ScreenUtil.getInstance().setHeight(50),
              margin: EdgeInsets.only(
                  bottom: ScreenUtil.getInstance().setHeight(15)),
              child: ListView.builder(
                  shrinkWrap: true,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      child: Container(
                        margin: EdgeInsets.only(right: 15),
                        decoration: BoxDecoration(
                            border: Border(
                                bottom: BorderSide(
                                    color: index == 0 ? white : mainColor,
                                    style: BorderStyle.solid))),
                        child: Text(_datas[index].name,
                            style: TextStyle(
                                color: index == 0 ? white : Colors.white70,
                                fontSize: ScreenUtil.getInstance().setSp(32))),
                      ),
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        if (index == 0) {
                          return;
                        }
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (context) {
                          return BrandGoodsPage(
                              type: _datas[index].cat_id,
                              cat_name: _datas[index].name);
                        }));
                      },
                    );
                  },
                  itemCount: _datas.length),
            ),
            Expanded(
                child: bannerData == null
                    ? SizedBox()
                    : Swiper(
                        autoplayDisableOnInteraction: true,
                        itemBuilder: (BuildContext context, int index) {
                          return new ClipRRect(
                            child: CachedNetworkImage(
                              imageUrl: Api.ImgBaseUrl + bannerData[index].img,
                              fit: BoxFit.fill,
                            ),
                            borderRadius: BorderRadius.circular(10.0),
                          );
                        },
                        itemCount: bannerData.length,
                        pagination: new SwiperPagination(
                            builder: DotSwiperPaginationBuilder(
                                color: Colors.grey,
                                activeColor: mainColor,
                                size: 7.0,
                                activeSize: 7.0)),
                        scrollDirection: Axis.horizontal,
                        autoplay: true,
                        duration: 10,
                        controller: contr,
                        onIndexChanged: (index) {
                          // setState(() {
                          //   if (bannerData != null)
                          //     // currentColor = hexToColor(bannerData[index].color);
                          // });
                        },
                        onTap: (index) {},
                      ))
          ],
        ));
  }

  initList() {
    return ListView.separated(
        controller: scrollController,
        itemBuilder: _renderRow,
        separatorBuilder: (BuildContext context, int index) {
          return Container(
            color: Colors.black45,
            height: 0.0,
          );
        },
        itemCount: goodsList.length + 2);
  }

  checkVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    int versionCode = int.parse(packageInfo.version.replaceAll(".", ""));
    Map map = new Map();
    map['sign_type'] = SignType.CHECK_VERSION;
    Response<String> response =
        await HttpUtil().post(Api.VERSION_CHECK, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      if (Platform.isAndroid) {
        isCheck = false;
      } else {
        isCheck = (userMap['data']['is_ios_check'] == "Y");
        saveBoolean("isCheck", isCheck);
      }
      if (Platform.isAndroid) {
        int service = int.parse(
            userMap['data']['version_android'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content: new Text('应用发现新的版本，是否下载更新'),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    downApk(userMap['data']['down_android']);
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即下载', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        }
      } else {
        int service = int.parse(
            userMap['data']['version_ios'].toString().replaceAll(".", ""));
        if (service > versionCode) {
          //做更新处理
          showDialog(
            context: context,
            builder: (context) => new AlertDialog(
              title: new Text('提示'),
              content: new Text('应用发现新的版本，是否前去下载'),
              actions: <Widget>[
                new FlatButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: new Text(
                    '取消',
                    style: TextStyle(color: Colors.grey),
                  ),
                ),
                new FlatButton(
                  onPressed: () async {
                    final url =
                        "https://itunes.apple.com/cn/app/id1502816436"; // id ��面的数字换成自己的应用 id 就行了
                    if (await canLaunch(url)) {
                      await launch(url, forceSafariVC: false);
                    } else {
                      throw 'Could not launch $url';
                    }
                    Navigator.of(context).pop(false);
                  },
                  child: new Text('立即前往', style: TextStyle(color: mainColor)),
                ),
              ],
            ),
          );
        }
      }
    }
  }

  downApk(String url) async {
    Directory dic;
    dic = await getExternalStorageDirectory();
    Response response;
    File file = File(dic.path +
        "/" +
        DateTime.now().millisecondsSinceEpoch.toString() +
        ".apk");
    if (!file.existsSync()) {
      file.createSync();
    }
    show();
    try {
      response = await new Dio().download(url, file.path,
          onReceiveProgress: (int count, int total) {
        percent = count * 1.00 / total;
        mystate(() {});
        // //进度
        // _showNotification(
        //     (count * 100 / total).toString().substring(0, 5) + '%');
      });
      if (response.statusCode == 200) {
        Navigator.of(context).pop(1);
        _installApk(file.path);
        // flutterLocalNotificationsPlugin.cancelAll();
        // Fluttertoast.showToast(msg: '下载成功');
      }
      // print('downloadFile success---------${response.data}');
    } on DioError catch (e) {
      Fluttertoast.showToast(msg: '下载出错');
      // print('downloadFile error---------$e');
    }
  }

  Future _showNotification(String str) async {
    //安卓的通知配置，必填参数是渠道id, 名称, 和描述, 可选填通知的图标，重要度等等。
    var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
        '1', 'xiongmao', 'xinogmao',
        importance: Importance.Max, priority: Priority.High);
    //IOS的通知配置
    var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
    var platformChannelSpecifics = new NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    //显示通知，其中 0 代表通知的 id，用于区分通知。
    await flutterLocalNotificationsPlugin.show(
        0, '更新服务正在运行', '已下载$str', platformChannelSpecifics,
        payload: 'complete');
  }

  double percent = 0;
  var mystate;
  show() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => new StatefulBuilder(
        builder: (context, setState) {
          mystate = setState;
          return new AlertDialog(
            title: Text('下载进度'),
            content: new LinearProgressIndicator(
              value: percent,
              valueColor: new AlwaysStoppedAnimation<Color>(mainColor),
              backgroundColor: Colors.grey,
            ),
          );
        },
      ),
    );
  }

  // 调用android代码安装apk
  void _installApk(String path) {
    const platform = MethodChannel("com.dmooo.panda/update");
    try {
      // 调用app地址
      platform.invokeMethod(
          'install', {"bundleId": "com.dmooo.panda", "path": path});
    } on PlatformException catch (_) {}
  }

  loadBanner() async {
    Map map = new Map();
    map['cat_id'] = "2";
    map['sign_type'] = SignType.GET_BANNER_LIST;
    Response<String> response =
        await HttpUtil().post(Api.GETBANNER, data: getSign(map));
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      BannerModelEntity bannerEntity = new BannerModelEntity.fromJson(userMap);
      setState(() {
        _controller.finishRefresh();
        bannerData = bannerEntity.data;
      });
    }
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index == 0) {
      return Container(
        child: initTop(),
      );
    }
    if (index == 1) {
      return Container(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(height: ScreenUtil.getInstance().setHeight(DP_10)),
            Container(
              decoration: BoxDecoration(
                  color: Color(0xffd9f2e9),
                  borderRadius: BorderRadius.circular(4)),
              padding: EdgeInsets.only(
                  top: ScreenUtil.getInstance().setHeight(DP_10 + 2),
                  bottom: ScreenUtil.getInstance().setHeight(DP_10 + 2)),
              margin: EdgeInsets.only(left: 15, right: 15),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_10),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_10),
                        0),
                    margin: EdgeInsets.fromLTRB(
                        ScreenUtil.getInstance().setHeight(DP_20),
                        0,
                        ScreenUtil.getInstance().setHeight(DP_20),
                        0),
                    child: Text('公告',
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(SMALL_FONT_SIZE - 2))),
                    decoration: BoxDecoration(
                        color: mainColor,
                        borderRadius: BorderRadius.circular(4)),
                  ),
                  Expanded(
                      child: GestureDetector(
                    child: Text(
                      articles.length == 0 ? "" : articles[current].title,
                      style: TextStyle(
                          color: Colors.black87,
                          fontSize:
                              ScreenUtil.getInstance().setSp(SMALL_FONT_SIZE)),
                    ),
                    onTap: () {
                      Navigator.of(context)
                          .push(MaterialPageRoute(builder: (context) {
                        return new ArticleDetailPage(
                          article_id: articles[current].article_id,
                        );
                      }));
                    },
                  ))
                ],
              ),
            ),
            Container(
              color: white,
              margin: EdgeInsets.only(top: 10),
              padding: EdgeInsets.fromLTRB(
                ScreenUtil.getInstance().setHeight(DP_30),
                ScreenUtil.getInstance().setHeight(20),
                ScreenUtil.getInstance().setHeight(DP_30),
                0,
              ),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: GestureDetector(
                      child: Center(
                        child: Column(
                          children: <Widget>[
                            Image.asset("images/home_menu_a.png"),
                            Container(
                              height: ScreenUtil.getInstance().setWidth(DP_8),
                            ),
                            Text(
                              '品牌馆',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE)),
                            ),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Container(
                              width: ScreenUtil.getInstance().setHeight(DP_40),
                              height: ScreenUtil.getInstance().setHeight(3),
                              color: white,
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (context) {
                          return PinPaiListPage();
                        }));
                      },
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      child: Center(
                        child: Column(
                          children: <Widget>[
                            Image.asset("images/home_menu_b.png"),
                            Container(
                              height: ScreenUtil.getInstance().setWidth(DP_8),
                            ),
                            Text(
                              '熊猫自营',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE)),
                            ),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Container(
                              width: ScreenUtil.getInstance().setHeight(DP_40),
                              height: ScreenUtil.getInstance().setHeight(3),
                              color: white,
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (context) {
                          return SelectTopGoodsPage();
                        }));
                      },
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      child: Center(
                        child: Column(
                          children: <Widget>[
                            Image.asset("images/home_menu_c.png"),
                            Container(
                              height: ScreenUtil.getInstance().setWidth(DP_8),
                            ),
                            Text(
                              '秒杀专区',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE)),
                            ),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Container(
                              width: ScreenUtil.getInstance().setHeight(DP_40),
                              height: ScreenUtil.getInstance().setHeight(3),
                              color: white,
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (context) {
                          return QiangGouPage();
                        }));
                      },
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      onTap: () {
                        Navigator.of(context)
                            .push(new MaterialPageRoute(builder: (context) {
                          return ZeroGoodsPage(type: 1);
                        }));
                      },
                      child: Center(
                        child: Column(
                          children: <Widget>[
                            Image.asset("images/home_menu_d.png"),
                            Container(
                              height: ScreenUtil.getInstance().setWidth(DP_8),
                            ),
                            Text(
                              '0元购',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE)),
                            ),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Container(
                              width: ScreenUtil.getInstance().setHeight(DP_40),
                              height: ScreenUtil.getInstance().setHeight(3),
                              color: white,
                            )
                          ],
                        ),
                      ),
                    ),
                  ),
                  Expanded(
                    child: GestureDetector(
                      child: Center(
                        child: Column(
                          children: <Widget>[
                            Image.asset("images/home_menu_e.png"),
                            Container(
                              height: ScreenUtil.getInstance().setWidth(DP_8),
                            ),
                            Text(
                              '店长特权',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE)),
                            ),
                            Container(
                              height: ScreenUtil.getInstance().setHeight(DP_10),
                            ),
                            Container(
                              width: ScreenUtil.getInstance().setHeight(DP_40),
                              height: ScreenUtil.getInstance().setHeight(3),
                              color: white,
                            )
                          ],
                        ),
                      ),
                      onTap: () {
                        if (APPLIC.userInfoMap == null) {
                          if (APPLIC.GG == 0)
                            Navigator.of(context)
                                .push(new MaterialPageRoute(builder: (context) {
                              return new WelComePage();
                            }));
                          return;
                        }
                        if (APPLIC.userInfoMap['user_msg']['group_id']
                                .toString() ==
                            "1") {
                          Navigator.of(context)
                              .push(new MaterialPageRoute(builder: (context) {
                            return new UserUpdateListPage();
                          }));
                          return;
                        }
                        var timeStamp = DateTime.now().millisecondsSinceEpoch;
                        String signstr = "agentId=405&machineCode=" +
                            APPLIC.userInfoMap['user_msg']['uid'].toString() +
                            "&timestamp=" +
                            timeStamp.toString();
                        String singstrs = signstr +
                            "&secretKey=Pe7HRBJYwQfpxCb3s5TGW3hXeWxhXKpH";
                        var content = new Utf8Encoder().convert(singstrs);
                        var digest = md5.convert(content);
                        String sign = hex.encode(digest.bytes).toUpperCase();
                        Navigator.push(
                            context,
                            MaterialPageRoute(
                                //导航打开新视图
                                builder: (context) => JYZPayPage(
                                    url:
                                        "http://tq.jfshou.cn/seller/app/classify?machineCode=" +
                                            APPLIC.userInfoMap['user_msg']
                                                    ['uid']
                                                .toString() +
                                            "&agentId=405&timestamp=" +
                                            timeStamp.toString() +
                                            "&sign=" +
                                            sign) //打开第二个页面，并传值，传递值的名称是model
                                ));
                      },
                    ),
                  ),
                ],
              ),
            ),
            // Container(
            //   height: 8,
            //   color: f0Color,
            // ),
            // Offstage(
            //   offstage: isCheck,
            //   child: GestureDetector(
            //     child: Image.asset("images/top.png"),
            //     onTap: () {
            //       Navigator.of(context)
            //           .push(new MaterialPageRoute(builder: (context) {
            //         return new TempPage();
            //       }));
            //     },
            //   ),
            // ),

            Container(
              height: 3,
              color: white,
            ),
            Container(
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Icon(Icons.star,
                        size: ScreenUtil.getInstance().setHeight(26),
                        color: black),
                    Container(width: 10),
                    Text('每日精选',
                        style: TextStyle(
                            color: black,
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE - 2))),
                    // Expanded(child: Center()),
                    // GestureDetector(
                    //     onTap: () {
                    //       Navigator.of(context)
                    //           .push(new MaterialPageRoute(builder: (context) {
                    //         return new ReviewGoodsPage();
                    //       }));
                    //     },
                    //     behavior: HitTestBehavior.opaque,
                    //     child: Text('更多',
                    //         style: TextStyle(
                    //             color: black,
                    //             fontSize: ScreenUtil.getInstance()
                    //                 .setSp(SMALL_FONT_SIZE)))),
                    // Icon(Icons.arrow_forward_ios, size: 15, color: black_99)
                  ],
                ),
                width: double.infinity,
                padding:
                    EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_10)),
                decoration: BoxDecoration(
                  color: Color(0xffd9f2e9),
                ),
                margin: EdgeInsets.only(
                  bottom: 5,
                  top: ScreenUtil.getInstance().setHeight(DP_10),
                )),
            // Container(
            //     color: mainColor,
            //     alignment: Alignment.centerLeft,
            //     margin: EdgeInsets.only(top: 10),
            //     padding: EdgeInsets.fromLTRB(
            //         ScreenUtil.getInstance().setHeight(DP_20),
            //         ScreenUtil.getInstance().setHeight(10),
            //         ScreenUtil.getInstance().setHeight(DP_20),
            //         ScreenUtil.getInstance().setHeight(DP_10)),
            //     child: Row(
            //       mainAxisAlignment: MainAxisAlignment.start,
            //       children: <Widget>[
            //         Image.asset("images/icon_daily.png", scale: 1.3),
            //         Container(width: 5),
            //         Text('每日精选',
            //             style: TextStyle(
            //                 color: white,
            //                 fontSize: ScreenUtil.getInstance()
            //                     .setSp(SMALL_FONT_SIZE)))
            //       ],
            //     )),
          ],
        ),
      );
    }
    return GestureDetector(
      child: Container(child: renderRow2(context, index), color: white),
      onTap: () {
        if ((int.parse(goodsList[index - 2].sales_volume) +
                int.parse(goodsList[index - 2].virtual_volume)) <
            int.parse(goodsList[index - 2].num)) {
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return GoodsDetailPage(
              goods_id: goodsList[index - 2].goods_id,
              img: goodsList[index - 2].img,
            );
          }));
        } else {
          Fluttertoast.showToast(msg: '亲宝贝已经售馨，下次早抢哦！');
        }
      },
    );
  }

  renderRow2(BuildContext context, int index) {
    index = index - 2;
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setHeight(DP_10),
          ScreenUtil.getInstance().setHeight(DP_20),
          1),
      decoration: BoxDecoration(
          color: white,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10))),
      child: Material(
        borderRadius:
            BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_10)),
        color: white,
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Stack(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.only(
                      topRight: Radius.circular(
                          ScreenUtil.getInstance().setHeight(DP_10)),
                      topLeft: Radius.circular(
                          ScreenUtil.getInstance().setHeight(DP_10))),
                  child: CachedNetworkImage(
                      imageUrl: Api.ImgBaseUrl + goodsList[index].img,
                      width: (MediaQuery.of(context).size.width +
                          40 -
                          ScreenUtil.getInstance().setHeight(DP_40)),
                      fit: BoxFit.cover,
                      height: (MediaQuery.of(context).size.width +
                              40 -
                              ScreenUtil.getInstance().setHeight(DP_40)) *
                          0.45),
                ),
                Offstage(
                  child: Container(
                      alignment: Alignment.center,
                      child: Text(
                        '已售罄',
                        style: TextStyle(color: white, fontSize: 13),
                      ),
                      decoration: BoxDecoration(
                          color: Color.fromARGB(125, 0, 0, 0),
                          borderRadius: BorderRadius.only(
                              topRight: Radius.circular(
                                  ScreenUtil.getInstance().setHeight(DP_10)),
                              topLeft: Radius.circular(
                                  ScreenUtil.getInstance().setHeight(DP_10)))),
                      width: (MediaQuery.of(context).size.width +
                          40 -
                          ScreenUtil.getInstance().setHeight(DP_40)),
                      height: 0.45 *
                          (MediaQuery.of(context).size.width +
                              40 -
                              ScreenUtil.getInstance().setHeight(DP_40))),
                  offstage: (int.parse(goodsList[index].sales_volume) +
                              int.parse(goodsList[index].virtual_volume)) >=
                          int.parse(goodsList[index].num)
                      ? false
                      : true,
                )
              ],
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_15),
                  ScreenUtil.getInstance().setHeight(DP_8)),
              child: Text(
                goodsList[index].goods_name,
                style: TextStyle(
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE),
                    color: black),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Row(children: <Widget>[
              Expanded(
                  child: Column(children: <Widget>[
                Padding(
                  padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setHeight(DP_15),
                      0,
                      ScreenUtil.getInstance().setHeight(DP_15),
                      ScreenUtil.getInstance().setHeight(DP_15)),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: <Widget>[
                      Text('团购价' + MONEY,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE),
                              color: black_99)),
                      Text(goodsList[index].price.toString(),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontWeight: FontWeight.bold,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE + 2),
                              color: black)),
                      Expanded(
                        child: Text(''),
                        flex: 1,
                      ),
                      Text('市场价$MONEY',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(MINI_FONT_SIZE),
                              color: black_99)),
                      Text(goodsList[index].old_price.toString(),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE - 3),
                              color: black)),
                      Expanded(
                        flex: 3,
                        child: Text(''),
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: EdgeInsets.fromLTRB(
                      ScreenUtil.getInstance().setHeight(DP_15),
                      0,
                      ScreenUtil.getInstance().setHeight(DP_15),
                      ScreenUtil.getInstance().setHeight(DP_15)),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      SizedBox(
                        width: ScreenUtil.getInstance().setHeight(25) *
                                goodsList[index].avatars.length.toDouble() +
                            12,
                        child: Stack(
                            alignment: AlignmentDirectional.topStart,
                            children: buildAvatar(goodsList[index].avatars)),
                      ),
                      Container(
                          width: ScreenUtil.getInstance().setHeight(DP_15)),
                      Text(
                          (int.parse(goodsList[index].sales_volume) +
                                      int.parse(
                                          goodsList[index].virtual_volume))
                                  .toString() +
                              '人已购',
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE - 2),
                              color: Colors.black45)),
                      // Expanded(
                      //   child: Center(),
                      // ),
                    ],
                  ),
                )
              ])),
              (int.parse(goodsList[index].sales_volume) +
                          int.parse(goodsList[index].virtual_volume)) >=
                      int.parse(goodsList[index].num)
                  ? new Container(
                      color: Colors.grey[300],
                      margin: EdgeInsets.only(right: 10),
                      padding: EdgeInsets.fromLTRB(10, 5, 10, 2),
                      child: Text("已售罄",
                          style: TextStyle(
                              color: white,
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(SMALL_FONT_SIZE))),
                    )
                  : GestureDetector(
                      child: Column(children: <Widget>[
                        new Container(
                          height: ScreenUtil.getInstance().setWidth(DP_40),
                          margin: EdgeInsets.only(right: 10),
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(DP_160),
                          decoration: new BoxDecoration(
                              color: Colors.white,
                              border: Border.all(width: 1, color: mainColor),
                              borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(3),
                                  topRight: Radius.circular(3))),
                          child: new Padding(
                            padding: EdgeInsets.only(left: 10.0, right: DP_10),
                            child: new Text(
                              (int.parse(goodsList[index].sales_volume) +
                                          int.parse(goodsList[index]
                                              .virtual_volume)) >=
                                      int.parse(goodsList[index].num)
                                  ? "售罄"
                                  : "限" + goodsList[index].num + "份",
                              style: new TextStyle(
                                  color: mainColor,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE - 2)),
                            ),
                          ),
                        ),
                        new Container(
                          height: ScreenUtil.getInstance().setWidth(DP_40),
                          margin: EdgeInsets.only(right: 10),
                          alignment: Alignment.center,
                          width: ScreenUtil.getInstance().setWidth(DP_160),
                          decoration: new BoxDecoration(
                              color: mainColor,
                              borderRadius: BorderRadius.only(
                                  bottomLeft: Radius.circular(3),
                                  bottomRight: Radius.circular(3))),
                          child: new Padding(
                            padding: EdgeInsets.only(left: 10.0, right: DP_10),
                            child: new Text(
                              "立即购买",
                              style: new TextStyle(
                                  color: Colors.white,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(SMALL_FONT_SIZE - 2)),
                            ),
                          ),
                        )
                      ]),
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        if ((int.parse(goodsList[index].sales_volume) +
                                int.parse(goodsList[index].virtual_volume)) <
                            int.parse(goodsList[index].num)) {
                          Navigator.of(context)
                              .push(new MaterialPageRoute(builder: (context) {
                            return GoodsDetailPage(
                                goods_id: goodsList[index].goods_id,
                                img: goodsList[index].img,
                                buyNow: 1);
                          }));
                        } else {
                          Fluttertoast.showToast(msg: '亲宝贝已经售馨，下次早抢哦！');
                        }
                      },
                    )
            ])
          ],
        ),
        elevation: 1,
      ),
    );
  }

  buildAvatar(List<GoodsListDataDatasTag> avatars) {
    List<Widget> list = new List();
    list.add(ClipOval(
      child: CachedNetworkImage(
          imageUrl: Api.ImgBaseUrl + avatars[0].avatar,
          width: ScreenUtil.getInstance().setHeight(35),
          height: ScreenUtil.getInstance().setHeight(35)),
    ));
    for (int i = 1; i < avatars.length; i++) {
      list.add(
        Positioned(
          left: ScreenUtil.getInstance().setHeight(25) * i.toDouble(),
          child: ClipOval(
            child: CachedNetworkImage(
                imageUrl: Api.ImgBaseUrl + avatars[i].avatar,
                width: ScreenUtil.getInstance().setHeight(35),
                height: ScreenUtil.getInstance().setHeight(35)),
          ),
        ),
      );
    }
    return list;
  }
}

class BottonClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    var path = Path();
    path.lineTo(0, 0);
    path.lineTo(0, size.height - 50);
    var firstControlPoint = Offset(size.width / 2, size.height - 100);
    var firstEndPont = Offset(size.width, size.height - 50);
    path.quadraticBezierTo(firstControlPoint.dx, firstControlPoint.dy,
        firstEndPont.dx, firstEndPont.dy);
    path.lineTo(size.width, size.height - 50);
    path.lineTo(size.width, 0);
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) {
    return false;
  }
}
